package org.eclipse.epsilon.emc.lom.dt.popup.actions;

import java.io.IOException;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.xmi.impl.XMIResourceFactoryImpl;
import org.eclipse.epsilon.emc.lom.LiveObjectModelBuilder;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

public class InjectModelToH2 implements IObjectActionDelegate {

	private Shell shell;
	
	IStructuredSelection selection = null;
	
	/**
	 * Constructor for Action1.
	 */
	public InjectModelToH2() {
		super();
	}

	/**
	 * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
	 */
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
		shell = targetPart.getSite().getShell();
	}

	/**
	 * @see IActionDelegate#run(IAction)
	 */
	public void run(IAction action) {
		
		IFile modelFile = (IFile) selection.getFirstElement();
		String modelFilePath = modelFile.getLocation().toOSString();
		
		String dbPath = modelFilePath.substring(0, modelFilePath.length() - 6);
		
		LiveObjectModelBuilder builder = new LiveObjectModelBuilder(dbPath);
		builder.createDatabase();
		
		ResourceSet resourceSet = new ResourceSetImpl();
		resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().
			put("*", new XMIResourceFactoryImpl());
		
		Resource resource = resourceSet.createResource(URI.createFileURI(modelFilePath));
		
		try {
			resource.load(null);
			builder.addResource(resource);
			modelFile.getParent().refreshLocal(IResource.DEPTH_INFINITE, new NullProgressMonitor());
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}

	/**
	 * @see IActionDelegate#selectionChanged(IAction, ISelection)
	 */
	public void selectionChanged(IAction action, ISelection selection) {
		this.selection = (IStructuredSelection) selection;
	}

}
